package com.jack.leetcode.eachProblem07;

import com.jack.leetcode.eachProblem06.二叉树中的最大路径和;

public class 将有序数组转换为二叉搜索树 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        sortedArrayToBST(nums);
    }

    public static TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null) {
            return null;
        }
        int n = nums.length;
        return midEach(0, n - 1, nums);
    }

    private static TreeNode midEach(int begin, int end, int[] nums) {
        int mid = (begin + end) / 2;
        if (begin > end) {
            return null;
        }
        TreeNode root = new TreeNode(nums[mid]);
        root.left = midEach(begin, mid - 1, nums);
        root.right = midEach(mid + 1, end, nums);
        return root;
    }
}
